<template>
  <div class="image-viewer" @click="backClick" v-show="show"  v-transfer-dom :data-transfer="true">
      <div class="image-box" @mousewheel="zoom">
          <img ref="img" :src="src"></img>
      </div>
      <div @click="close" class="imgage-close">
        <Icon type="close-circled" ></Icon>
      </div>
  </div>
</template>

<script>
import Drag from "@/common/drag";
import TransferDom from "@/directives/transfer-dom";

export default {
  name: "imageViewer",
  props: {
    value: {
      default: false
    },
    src: {}
  },
  data() {
    return {
      show: this.value
    };
  },
  mounted() {
    Drag(this.$el, this.$refs.img);
  },
  watch: {
    value(v) {
      if (v) this.resetImgStyle();
      this.show = v;
    }
  },
  methods: {
    zoom(e) {
      var o = e.target;
      var zoom = parseInt(o.style.zoom, 10) || 100;
      zoom += event.wheelDelta / 9;
      if (zoom > 0) o.style.zoom = zoom + "%";
      return false;
    },
    backClick(e) {
      if (e.target === e.currentTarget) {
        this.close();
      }
    },
    close() {
      this.show = false;
      this.$emit("input", false);
    },
    open() {
      this.show = true;
      this.$emit("input", true);
    },
    resetImgStyle() {
      this.$refs.img.style.left = 0;
      this.$refs.img.style.top = 0;
      this.$refs.img.style.zoom = "100%";
      this.$nextTick(() => {
        //计算默认放大大小，使超过图片初始大小不超过屏幕
        this.zoomCompute();
      });
    },
    zoomCompute() {
      var maxHeight = window.innerHeight - 40;
      var maxWidth = window.innerWidth - 40;
      var height = this.$refs.img.offsetHeight;
      var width = this.$refs.img.offsetWidth;
      var zoom = 1;
      if (maxHeight < height || maxWidth < width) {
        if (height > width) {
          zoom = maxHeight / height;
        } else {
          zoom = maxWidth / width;
        }
        this.$refs.img.style.zoom = zoom * 100 + "%";
      }
    }
  },
  directives: {
    TransferDom
  }
};
</script>

<style lang="less">
.image-viewer {
  position: fixed;
  height: 100%;
  width: 100%;
  z-index: 30000;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.6);
  img {
    cursor: move;
    position: relative;
    left: 0;
    top: 0;
  }
  .imgage-close {
    right: 8px;
    top: 4px;
    position: absolute;
    font-size: 36px;
    color: #6b6b6b;
    cursor: pointer;
    &:hover {
      color: #949494;
    }
  }
}
</style>
